<?php

// +----------------------------------------------------------------------
// | POS机回调
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\controller\api\notify;

use app\event\ucenter\MemberInfo;
use app\event\ucenter\User as UserEvent;
use app\model\pos\Pos as PosModel;
use app\model\pos\PosTrade as PosTradeModel;
use app\model\pos\Store as StoreModel;
use app\event\pos\PosTrade as PosTradeEvent;
use app\model\ucenter\MemberInfo as MemberInfoModel;
use app\model\ucenter\User as UserModel;
use app\model\ucenter\UserMoneyLog;
use app\model\app\GameOrder as GameOrderModel;
use app\model\ucenter\UserTask as UserTaskModel;
use think\Exception;
use think\facade\Db;
use think\facade\Log;
use yicmf\tools\Rsa;

class Xwan extends Common
{

    private function _getData()
    {
        $data = $this->request->param();
//        $data = '{"data":"FPfJRH4CHQ0L8BW3R2+EIBUccna727wmq\/4eT0wCyt+IcHSmvn99IlYGc3mUtsznyU8m43kjC3hTeUOQ3HLN0SkFkoM9sxoME5Gq17moyELp1GZFuQYZJFHMyI+WsSzFsSQzEPpMcEGIaN73tnzVc+JhY+P3kScC0GJJiIu1Wc10Tyj\/L8UewzkWr5qJaJzQ73q6R3OmggWyVkUJDhEMYd+7NPLk+RjpODp07Xbc4jtWU3vmW2eiCVqEEJrhE4S+9+607xQ1dWEvWk45FWGUKtJhTIWN0Obiai5U8yUyWHSrEMe8\/EfsHogbMbhTGkgh3GJc461JrjRGe1IsJQHvcHRcfWXFEvrnsbMNDVL5zZAGK\/P\/4+wsi2reK8srMy\/e0e9By3MdkT+0UZMLbxETyff\/LNVn3al0eAYAPN68\/JVekdUopvTzQLarJswwx1lj84RxpOuAtfFf4ZRko+0qmVH00OzkHdmS4F\/IPzuQrv7ApURLoMT1Fr1nxdWrxR8f","id":"119364425211123","controller":"la","action":"trade"}';
//        $data = json_decode($data, true);
//        $data = ['adid' => '42281',
//            'adname' => '英雄与地下城-Ⅰ期',
//            'appid' => '12914',
//            'ordernum' => '12914202411141558334228112R3U4',
//            'dlevel' => '1',
//            'pagename' => 'com.ctwlkj.yxydxc',
//            'deviceid' => '3ac4ffadd48935dc863db2cb4a9ac2c7',
//            'simid' => '3ac4ffadd48935dc863db2cb4a9ac2c7',
//            'appsign' => 'undefined',
//            'merid' => '731569999',
//            'event' => '英雄与地下城-Ⅰ期消除乐园通过第1关',
//            'price' => '0.8',
//            'money' => '0.4',
//            'itime' => '2024/11/14 15:58:33',
//            'adicon' => 'https://cimgs.17xianwan.com/corp-document/202411/05105200013.jpg',
//            'atype' => '2',
//            'keycode' => '717DD3E033C42ED71E0BD18ABF7AEDFE',
//            'controller' => 'xwan',
//            'action' => 'task'];
        Log::write($data);
        if (isset($data['keycode'])) {
            $keycode = $data['keycode'];
            if ($data['appid'] == '12914') {
                $md5 = md5($data['adid'] . $data['appid'] . $data['ordernum'] . $data['dlevel'] . $data['deviceid'] . $data['appsign'] . $data['price'] . $data['money'] . '1QMUW0uvkFY89EK1');
            } else {
                $md5 = md5($data['adid'] . $data['appid'] . $data['ordernum'] . $data['dlevel'] . $data['deviceid'] . $data['appsign'] . $data['price'] . $data['money'] . 'cY38t2PMo2sw1F4P');
            }
            if ($keycode == strtoupper($md5)) {
                return $data;
            } else {
                return false;
            }
        } else {
            return false;
        }

    }


    /**
     * 参数名    类型    最大长度    说明
     * adid    Int    10    广告ID (adid=1 特殊活动 price=money)
     * adname    String    200    广告名称
     * appid    String    10    开发者ID
     * ordernum    String    100    订单编号
     * dlevel    Int    10    奖励级别
     * pagename    String    100    用户体验游戏的包名
     * atype    int    10    任务奖励类型（2：等级奖励 9：充值奖励 -1：活动奖励 其他：待定）
     * deviceid    String    100    手机设备号 imei 或 idfa
     * simid    String    100    手机sim卡id
     * appsign    String    100    开发者用户编号（用户id）
     * merid    String    100    用户体验游戏注册的账号id
     * event    String    800    奖励说明—在开发者自己的APP中需显示给用户看，以便用户了解自己获得的奖励
     * adicon    String    100    广告icon图片地址 ；需URL解码
     * price    String    20    闲玩结算给开发者结算单价、单位：元 （最多保留2位小数）
     * money    String    20    开发者需奖励给用户金额 单位：元 （最多保留2位小数）。利润=price-money
     * itime    Date    20    用户获得奖励时间 时间字符串 如：2018/01/24 12:13:24
     * keycode    String    100    订单校验参数 加密规则
     * MD5(adid+appid+ordernum+dlevel+deviceid
     * +appsign+price+money+key)
     * + 为连接符不做加密 [MD5加密结果需转大写]
     * price与money存在整数的情况，请直接使用传过来的值进行加密或转string后再进行加密校验；避免传值为1但开发者加密的时候却变成1.0的情况出现
     * 备注：加密Key请向闲玩获取；
     * 接入者即为开发者
     * */
    public function task()
    {
        $data = $this->_getData();
        if ($data) {
            try {
                $game = GameOrderModel::where('ordernum', $data['ordernum'])
                    ->where('appid', $data['appid'])
                    ->where('adid', $data['adid'])
                    ->where('merid', $data['merid'])
                    ->find();
                if ($game) {
                    throw new Exception('已经记录');
                }
                $data['task_time'] = $data['itime'];
                $data['user_id'] = $data['appsign'];
                $game = GameOrderModel::create($data);
                Db::startTrans();
                $user = UserModel::where('id', $game['appsign'])->lock(true)->find();
                if (!$user) {
                    throw new Exception('用户信息异常');
                }
                $userTask['task_id'] = 6;
                $userTask['relation_id'] = $game['id'];
                $userTask['task_type'] = 20;
                $userTask['user_id'] = $user['id'];
                $userTask['agent_id'] = $user['agent_id'];
                $userTask['title'] = $data['event'];
                $userTask['money'] = $data['price'];
                $userTask['commission'] = $data['money'];
                $userTask['task_no'] = $data['ordernum'];
                $userTask['logo'] = $data['adicon'];
                $userTask['step'] = 2;
                $userTask['submit_info'] = $data;
                $userTask['status'] = 2;

                $task = $user->tasks()->save($userTask);
                if (!$task) {
                    throw new Exception('保存失败');
                }
                UserEvent::exhibitionIncome($user, $userTask['commission'], $data['adname'], 37, $user['id'], $task['task_no'], 0, $data['appid'],6);
                Db::commit();
                $rep = ['success' => 1, 'message' => '接收成功'];
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $rep = ['success' => 0, 'message' => $e->getMessage()];
            }
        } else {
            $rep = ['success' => 0, 'message' => '密钥校验失败'];
        }
        return json($rep);
    }

}
